package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.EstateAgency;
import com.pms.entity.HouseMasterInfo;
import com.pms.entity.UnitHouse;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.IEstateAgencyService;
import com.pms.service.IHouseMasterInfoService;
import com.pms.service.IUnitHouseService;
import com.pms.util.DateUtil;
import com.pms.util.ExcelReadUtil;
import com.pms.util.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 *  户主信息 不设删除功能，删除房屋后自动删除
 * </p>
 *
 * @author ASUS_B
 * @since 2017-11-02
 */
@RestController
@RequestMapping("/houseMasterInfoBase")
@Api(value="户主信息管理界面接口",description = "户主信息管理界面接口")
public class HouseMasterInfoController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IHouseMasterInfoService houseMasterInfoService;
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Value("${excel.read.templatepath}")
    private String excelTemplatePath;
    @Value("${excel.write.errHouseMasterPath}")
    private String excelErrHouseMasterPath;

    @ApiOperation(value = "添加单个户主信息")
    @RequestMapping(value = "/addHouseMasterInfo",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="houseMasterName",value="户主姓名",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseMasterSex",value="户主性别(1-男，2-女，3-保密(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="houseMasterPhone",value="户主手机联系电话(后4位)phone和telphone必须有一个",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseMasterTelphone",value="户主座机联系电话,phone和telphone必须有一个",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="unitName",value="单元名称",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseNumber",value="房号",required = true,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseProportion",value="户室面积",required = true,dataType = "double",paramType="form"),
    })
    public R addHouseMasterInfo(Long communityId,String houseMasterName,Integer houseMasterSex,String houseMasterPhone,String houseMasterTelphone
            ,String unitName,String houseNumber,Double houseProportion){
        parameterIsNull(communityId,"社区id不能为空");
        parameterIsBlank(houseMasterName,"请填写户主姓名");
        if(houseMasterName.length()>18){return R.error(400,"户主姓名过长");}
        parameterIsBlank(unitName,"请填写单元名称");
        parameterIsBlank(houseNumber,"请填写房号");
        parameterIsNull(houseProportion,"请填写户室面积");
        if(houseProportion<=0){ return R.error(400,"户室面积必须大于0");}
        if(StringUtils.isBlank(houseMasterPhone)&&StringUtils.isBlank(houseMasterTelphone)){return R.error(400,"请填写户主联系电话");}
        boolean phoneTag = false;
        if(StringUtils.isNotBlank(houseMasterPhone)){
            if(houseMasterPhone.trim().length()==4){ phoneTag = true;
            }else{
                if(ValidateUtil.validatePhone(houseMasterPhone)){  phoneTag = true;}
            }
        }
        if(!phoneTag){ return R.error(400,"该手机号码格式不正确");}
        boolean telphoneTag = false;
        if(StringUtils.isNotBlank(houseMasterTelphone)){
           if(ValidateUtil.validateTelphone_(houseMasterTelphone)){  telphoneTag = true;}
        }
        if(!telphoneTag){return R.error(400,"该座机号码格式不正确");}
        EstateAgency community =agencyService.selectById(communityId);
        parameterIsNull(community,"没有该社区信息");
        if(community.getAgencyType()==null||community.getAgencyType()!=2){
            return R.error(400,"该机构不属于社区");
        }
        houseNumber = houseNumber.trim();
        if(houseNumber.length()<3){ return R.error(400,"该房号不符合规则");}
        Wrapper<UnitHouse> countHouseWrapper= new EntityWrapper<UnitHouse>().eq("unit_name",unitName);
        countHouseWrapper.eq("house_number",houseNumber);
        countHouseWrapper.eq("community_id",community.getAgencyId());
        UnitHouse house = unitHouseService.selectOne(countHouseWrapper);
        if(null==house){return R.error(400,"没有该房室信息，无法添加户主信息");}
        if(null!=house.getIsHaveMaster()&&house.getIsHaveMaster()==2){return R.error(400,"该房室已有户主信息，无法重复添加");}
        if(null!=houseMasterSex){
            if(houseMasterSex!=1&&houseMasterSex!=2){houseMasterSex=3;}
        }
        if(houseMasterSex==null){houseMasterSex=3;}
        HouseMasterInfo addHouseMasterInfo = new HouseMasterInfo();
        addHouseMasterInfo.setCommunityId(community.getAgencyId());
        addHouseMasterInfo.setHouseMasterName(houseMasterName);
        if(phoneTag){addHouseMasterInfo.setHouseMasterPhone(houseMasterPhone);}
        if(telphoneTag){addHouseMasterInfo.setHouseMasterTelphone(houseMasterTelphone);}
        addHouseMasterInfo.setHouseNumber(houseNumber);
        addHouseMasterInfo.setHouseMasterSex(houseMasterSex);
        addHouseMasterInfo.setHouseProportion(houseProportion);
        addHouseMasterInfo.setUnitName(unitName);
        addHouseMasterInfo.setFloorSort(Integer.parseInt(houseNumber.substring(0,houseNumber.length()-2)));
        addHouseMasterInfo.setHouseId(house.getHouseId());
        addHouseMasterInfo.setFloorId(house.getFloorId());
        addHouseMasterInfo.setUnitId(house.getUnitId());
        addHouseMasterInfo.setAgencyId(house.getAgencyId());
        houseMasterInfoService.insert(addHouseMasterInfo);
        /** 修改户室对应房屋面积*/
        UnitHouse editHouse = new UnitHouse();
        editHouse.setHouseProportion(addHouseMasterInfo.getHouseProportion());
        editHouse.setIsHaveMaster(2);
        unitHouseService.update(editHouse,countHouseWrapper);
        return R.ok();
    }
    @ApiOperation(value = "修改户主信息")
    @RequestMapping(value = "/editHouseMasterInfo",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseMasterId",value="户主信息id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="houseMasterName",value="户主姓名",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseMasterSex",value="户主性别(1-男，2-女，3-保密(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="houseMasterPhone",value="户主手机联系电话(后4位)phone和telphone必须有一个",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseMasterTelphone",value="户主座机联系电话,phone和telphone必须有一个",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseProportion",value="户室面积",required = false,dataType = "double",paramType="form"),
    })
    public R editHouseMasterInfo(Long houseMasterId,String houseMasterName,Integer houseMasterSex,String houseMasterPhone
            ,String houseMasterTelphone,Double houseProportion){
        parameterIsNull(houseMasterId,"户主信息id不能为空");
        HouseMasterInfo editHouseMasterInfo =houseMasterInfoService.selectById(houseMasterId);
        parameterIsNull(editHouseMasterInfo,"没有该户主信息");
        boolean editTag = false;
        boolean editProportionTag = false;
        if(StringUtils.isNotBlank(houseMasterName)){
            if(houseMasterName.length()>18){return R.error(400,"户主姓名内容过长");}
            if(!houseMasterName.equals(editHouseMasterInfo.getHouseMasterName())){
                editTag = true;editHouseMasterInfo.setHouseMasterName(houseMasterName);
            }
        }
        if(null!=houseMasterSex){
            if(houseMasterSex!=1&&houseMasterSex!=2){houseMasterSex=3;}
            if(houseMasterSex!=editHouseMasterInfo.getHouseMasterSex()){editTag = true;editHouseMasterInfo.setHouseMasterSex(houseMasterSex);}
        }
        if(StringUtils.isNotBlank(houseMasterPhone)){
            houseMasterPhone = houseMasterPhone.trim();
            if(houseMasterPhone.length()==4){
                if(!houseMasterPhone.equals(editHouseMasterInfo.getHouseMasterPhone())){
                    editTag = true;
                    editHouseMasterInfo.setHouseMasterPhone(houseMasterPhone);
                }
            }
            if(houseMasterPhone.length()!=4){
                if(!ValidateUtil.validatePhone(houseMasterPhone)){return R.error(400,"该手机号码格式有误");}
                if(!houseMasterPhone.equals(editHouseMasterInfo.getHouseMasterPhone())){
                    editTag = true;
                    editHouseMasterInfo.setHouseMasterPhone(houseMasterPhone);
                }
            }
        }
        if(StringUtils.isNotBlank(houseMasterTelphone)){
            if(!ValidateUtil.validateTelphone_(houseMasterTelphone)){ return R.error(400,"该座机号码格式有误");}
            if(!houseMasterTelphone.equals(editHouseMasterInfo.getHouseMasterTelphone())){
                editTag = true;
                editHouseMasterInfo.setHouseMasterTelphone(houseMasterTelphone);
            }
        }
        if(null!=houseProportion){
            if(houseProportion<=0){return R.error(400,"户室面积必须大于0");}
            if(houseProportion!=editHouseMasterInfo.getHouseProportion()){
                editTag = true;
                editProportionTag = true;
                editHouseMasterInfo.setHouseProportion(houseProportion);
            }
        }
        if(editTag){
            houseMasterInfoService.updateById(editHouseMasterInfo);
            if(editProportionTag){//修改房屋户室面积
                UnitHouse editHouse = new UnitHouse();
                editHouse.setHouseProportion(editHouseMasterInfo.getHouseProportion());
                Wrapper<UnitHouse> countHouseWrapper= new EntityWrapper<UnitHouse>();
                countHouseWrapper.eq("unit_name",editHouseMasterInfo.getUnitName());
                countHouseWrapper.eq("house_number",editHouseMasterInfo.getHouseNumber());
                countHouseWrapper.eq("community_id",editHouseMasterInfo.getCommunityId());
                unitHouseService.update(editHouse,countHouseWrapper);
            }
        }
        return R.ok();
    }
    @ApiOperation(value = "查询户主信息详情")
    @RequestMapping(value = "/readInfo",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseMasterId",value="户主信息id",required = true,dataType = "long",paramType="form"),
    })
    public R readInfo(Long houseMasterId){
        parameterIsNull(houseMasterId,"请选择户主信息");
        HouseMasterInfo editHouseMasterInfo =houseMasterInfoService.selectById(houseMasterId);
        parameterIsNull(editHouseMasterInfo,"暂无该户主信息");
        return R.ok().put("data",editHouseMasterInfo).putDescription(HouseMasterInfo.class);
    }

    @ApiOperation(value = "分页查询户主信息")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitName",value="单元名称",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="houseMasterName",value="户主姓名-模糊查询",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="floorSort",value="楼层",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="sortBy",value="房号排序(1-升序显示，2-降序显示)-默认根据添加时间排序",required = false,dataType = "int",paramType="form"),
    })
    public R readPage(Integer pageSize,Integer pageNum,Long communityId,String unitName,Integer floorSort,Integer sortBy,Long agencyId,String houseMasterName) {
        parameterIsNull(agencyId,"物业机构id不能为空");
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        Page<HouseMasterInfo> page = new Page<HouseMasterInfo>(pageNum,pageSize);
        Wrapper<HouseMasterInfo> wrapper=  new EntityWrapper<HouseMasterInfo>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=communityId){
            wrapper.eq("community_id",communityId);
        }
        if(StringUtils.isNotBlank(unitName)){
            wrapper.eq("unit_name",unitName);
        }
        if(null!=floorSort){
            wrapper.eq("floor_sort",floorSort);
        }
        if(StringUtils.isNotBlank(houseMasterName)){
            wrapper.like("house_master_name",houseMasterName);
        }
        if(sortBy!=null){ if(sortBy!=1&&sortBy!=2){sortBy=null;} }
        //默认根据 id 降序排序
        if(sortBy==null){wrapper.orderBy("house_master_id",false);}
        if(sortBy!=null){
            wrapper.orderBy("unit_id",true);
            wrapper.orderBy("floor_sort",true);
            if(sortBy==1){wrapper.orderBy("house_number",true);}
            if(sortBy!=1){wrapper.orderBy("house_number",false);}
        }
        Page<HouseMasterInfo> returnPage = houseMasterInfoService.selectPage(page,wrapper);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(UnitHouse.class);
    }

    @ApiOperation(value = "excel导入户主信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="社区id-必传(参数优先,请求头也行)",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="file",value="",required = false,dataType = "file",paramType="form"),
    })
    @RequestMapping(value = "/importHouseMasterList",method =RequestMethod.POST)
    public R importData(HttpServletRequest request, ModelMap modelMap) throws Exception{
        //声明 错误的 list
        List<HouseMasterInfo> list = new ArrayList<HouseMasterInfo>();
        //  excel中 正确的 数据
        List<HouseMasterInfo> excelList = new ArrayList<HouseMasterInfo>();
        Long communityId = null;
        try {
            String communityIdStr = request.getParameter("communityId");
            if(StringUtils.isBlank(communityIdStr)){
                communityIdStr = request.getHeader("communityId");
            }
            if(StringUtils.isBlank(communityIdStr)){return R.error(400,"社区id不能为空");}
            try{
                communityId = Long.parseLong(communityIdStr);
            }catch(NumberFormatException ex){return R.error(400,"社区id类型错误");}
            EstateAgency community = agencyService.selectById(communityId);
            parameterIsNull(community,"没有该社区信息");
            if(community.getAgencyType()==null||community.getAgencyType()!=2){return R.error(400,"该机构不属于社区");}
            //查询小区 所有 没有户主信息 的房屋
            List<UnitHouse> unitHouseList =unitHouseService.selectList(new EntityWrapper<UnitHouse>().eq("community_id",communityId).eq("is_have_master",1));
            //直接使用，无需配置=》将当前上下文初始化给CommonsMutipartResolver(创建多部分解析器)
            CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver( request.getSession().getServletContext());
            //设置编码
            multipartResolver.setDefaultEncoding("utf-8");
            //检查request中是否有 文件上传=》enctype="multipart/form-data"
            if(multipartResolver.isMultipart(request)){
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator iter=multiRequest.getFileNames();
                boolean fileIterTag = true;
                while(iter.hasNext()){
                    if(fileIterTag){fileIterTag=false;}
                    //一次遍历所有文件
                    MultipartFile file=multiRequest.getFile(iter.next().toString());
                    if(file!=null){
                        String filePath =file.getOriginalFilename();
                        String fileType = filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
                        InputStream stream = file.getInputStream();
                        Workbook wb = null;
                        if (fileType.equals("xls")) {
                            wb = new HSSFWorkbook(stream);
                        } else if (fileType.equals("xlsx")) {
                            wb = new XSSFWorkbook(stream);
                        } else {
                            return R.error(400,"该excel文件格式不正确");
                        }
                        // 去重 excel 中 重复的 数据
                        List<HouseMasterInfo> distinctExcelList = new ArrayList<HouseMasterInfo>();//增加的代码
                        Sheet sheet1 = wb.getSheetAt(0);
                        for (int i = 1; i <= sheet1.getLastRowNum(); i++) {
                            HouseMasterInfo distinctHousehoiders = new HouseMasterInfo();//增加的代码，判断是否重复
                            HouseMasterInfo househoiders = new HouseMasterInfo();
                            Row titleRow = sheet1.getRow(0); //标题 不取
                            Row row = sheet1.getRow(i);
                            String name= ExcelReadUtil.getValue((Cell) row.getCell(0)).trim();
                            String sex = ExcelReadUtil.getValue((Cell) row.getCell(1)).trim();
                            String phone = ExcelReadUtil.getValue((Cell) row.getCell(2)).trim();
                            String telephone = ExcelReadUtil.getValue((Cell) row.getCell(3)).trim();
                            String houseNumber = ExcelReadUtil.getValue((Cell) row.getCell(4)).trim();
                            String unit = ExcelReadUtil.getValue((Cell) row.getCell(5)).trim();
//                            String address = ExcelReadUtil.getValue((Cell) row.getCell(6));
                            String area = ExcelReadUtil.getValue((Cell) row.getCell(6)).trim();
                            househoiders.setHouseMasterName(name);
                            if("男".equals(sex)){
                                househoiders.setHouseMasterSex((Integer)1);
                            }else if("女".equals(sex)){
                                househoiders.setHouseMasterSex((Integer) 2);
                            }else {
                                househoiders.setHouseMasterSex(3);
                            }
                            househoiders.setHouseNumber(houseNumber);
                            househoiders.setUnitName(unit);
                            househoiders.setCommunityId(communityId);
                            //去重对象
                            distinctHousehoiders.setHouseNumber(houseNumber);//增加的代码
                            distinctHousehoiders.setUnitName(unit);//增加的代码
                            /*==========基础信息验证================*/
                            boolean phoneTag = false;
                            if(StringUtils.isNotBlank(phone)){
                                if(phone.length()==4){
                                    phoneTag = true;
                                    househoiders.setHouseMasterPhone(phone);
                                }else{
                                    if(ValidateUtil.validatePhone(phone)){  //电话号码验证
                                        phoneTag = true;
                                        househoiders.setHouseMasterPhone(phone);
                                    }
                                }
                            }
                            if(ValidateUtil.validateTelphone_(telephone)){ // 座机号码验证
                                phoneTag = true;
                                househoiders.setHouseMasterTelphone(telephone);
                            }
                            if(!phoneTag){
                                if(StringUtils.isNotBlank(phone)){
                                    househoiders.setHouseMasterPhone(phone);
                                }
                                if(StringUtils.isNotBlank(telephone)){
                                    househoiders.setHouseMasterTelphone(telephone);
                                }
                                househoiders.setExcelErrRemarks("联系方式格式错误");
                                list.add(househoiders);// 号码格式不正确的
                                continue;
                            }
                            Double houseProportion =null;
                            try{
                                houseProportion = Double.valueOf(area);
                                if(houseProportion<=0){
                                    houseProportion = null;
                                    househoiders.setExcelErrRemarks("住宅面积必须大于0:"+area);
                                    list.add(househoiders);// 号码格式不正确的
                                }
                            }catch (NumberFormatException ex){
                                househoiders.setExcelErrRemarks("住宅面积格式错误:"+area);
                                list.add(househoiders);// 号码格式不正确的
                                continue;
                            }
                            househoiders.setHouseProportion(houseProportion);
                            if(StringUtils.isBlank(name)){
                                househoiders.setExcelErrRemarks("户主姓名不能为空");
                                list.add(househoiders);//增加的代码
                                continue;
                            }
                            if(name.length()>=20){
                                househoiders.setExcelErrRemarks("户主姓名过长");
                                list.add(househoiders);//增加的代码
                                continue;
                            }
                            if(StringUtils.isBlank(houseNumber)){
                                househoiders.setExcelErrRemarks("房号不能为空");
                                list.add(househoiders);//增加的代码
                                continue;
                            }
                            if(StringUtils.isBlank(unit)){
                                househoiders.setExcelErrRemarks("单元名称不能为空");
                                list.add(househoiders);
                                continue;
                            }
                            /*==================判断excel中数据是否重复======================*/
                            //判断 是否重复  需 移除id
                            distinctHousehoiders.setHouseMasterId(null);
                            if(!distinctExcelList.contains(distinctHousehoiders)){//增加的代码
                                distinctExcelList.add(distinctHousehoiders);//增加的代码
                            }else{//增加的代码
                                househoiders.setExcelErrRemarks("重复数据");
                                list.add(househoiders);//  excel中重复的
                                continue;//增加的代码
                            }
                            /*==================判断房间是否存在======================*/
                            for(int x=0;x<unitHouseList.size();x++){
                                if(houseNumber.equals(unitHouseList.get(x).getHouseNumber())&&unit.equals(unitHouseList.get(x).getUnitName())){
                                    househoiders.setHouseId(unitHouseList.get(x).getHouseId());
                                    househoiders.setFloorId(unitHouseList.get(x).getFloorId());
                                    househoiders.setUnitId(unitHouseList.get(x).getUnitId());
                                    break;
                                }
                            }
                            if(null==househoiders.getHouseId()){//没有该房间信息
                                househoiders.setExcelErrRemarks("暂无该户室信息 或 该户室已导入户主信息");
                                list.add(househoiders);//增加的代码
                                continue;
                            }
                            househoiders.setFloorSort(Integer.parseInt(houseNumber.substring(0,houseNumber.length()-2)));
                            househoiders.setAgencyId(community.getParentId());
                            excelList.add(househoiders);
                        }
                    }
                }
                if(fileIterTag){return R.error(400,"请上传户主信息excel文件");}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //查询小区下的 所有 户主信息
        List<HouseMasterInfo> existList = houseMasterInfoService.selectList(new EntityWrapper<HouseMasterInfo>().eq("community_id",communityId));
        List<HouseMasterInfo> excelListCopy = new ArrayList<HouseMasterInfo>();
        if(null!=existList&&!existList.isEmpty()){
            if(!excelList.isEmpty()){
                for(int x=0;x<excelList.size();x++){
                    boolean repetitionTag = false;
                    for(int y=0;y<existList.size();y++){
                        if(excelList.get(x).getHouseId().longValue()==existList.get(y).getHouseId().longValue()){
                            repetitionTag = true;
                            break;
                        }
                    }
                    if(repetitionTag){
                        excelList.get(x).setExcelErrRemarks("该户室已导入户主信息");
                        list.add(excelList.get(x));
                    }
                    if(!repetitionTag){
                        excelListCopy.add(excelList.get(x));
                    }
                }
            }
        }
        if(null==existList||existList.isEmpty()){
            excelListCopy.addAll(excelList);
        }
        if(!excelListCopy.isEmpty()){
            insertExcel_HouseMasterInfo(excelListCopy);
        }
        if(!list.isEmpty()){
            File csfile = new File(excelErrHouseMasterPath+File.separator+communityId);
            if(!csfile.exists()){
                csfile.mkdirs();
            }
            writeErrExcelData(list,csfile.getPath());
        }
        return R.ok().put("errSize",list.size()).putDescription("{errSize:导入数据的错误条数}");
    }

    @ApiOperation(value = "excel导入模板下载")
    @RequestMapping(value = "/downloadExcel",method =RequestMethod.POST ,produces="application/octet-stream")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = new File(excelTemplatePath+File.separator+"estateManagement.xls");
        String fileName = "物业户主信息导入模板.xls";
        // 读到流中
        InputStream inStream = new FileInputStream(file);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename="
                + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inStream.read(b)) > 0){
            response.getOutputStream().write(b, 0, len);
        }
        inStream.close();
    }
    @ApiOperation(value = "excel错误数据列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
    })
    @RequestMapping(value = "/getErrExcel",method =RequestMethod.POST)
    public Object getErrExcel(HttpServletRequest request, ModelMap modelMap,Long communityId) throws Exception {
        parameterIsNull(communityId,"社区id不能为空");
        String realPathUrl = request.getServletContext().getRealPath("");
        File csfile = new File(excelErrHouseMasterPath+File.separator+communityId);
        String [] names = csfile.list();
        return R.ok().put("data",names).put("description","{data:错误数据Excel表格名称-数组}");
    }
    @ApiOperation(value = "错误数据下载")
    @RequestMapping(value = "/downloadErrExcel" ,produces="application/octet-stream",method =RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name="communityId",value="社区id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="name",value="excel文件名称",required = true,dataType = "string",paramType="form"),
    })
    public void downloadErrExcel(HttpServletRequest request, HttpServletResponse response,String name,Long communityId) throws Exception {
        File csfile = new File(excelErrHouseMasterPath+File.separator+communityId+File.separator+name);
        if(!csfile.exists()){
            throw new RRException("该文件暂不存在",400);
        }
        String fileName = name;
        // 读到流中
        InputStream inStream = new FileInputStream(csfile);// 文件的存放路径
        // 设置输出的格式
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=GB2312");
        response.setCharacterEncoding("GB2312");
        response.setHeader("Content-Disposition", "attachment; filename="
                + new String(fileName.getBytes("GB2312"), "iso-8859-1"));
        // 循环取出流中的数据
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inStream.read(b)) > 0){
            response.getOutputStream().write(b, 0, len);
        }
        inStream.close();
    }
    /**
     * 插入 户主信息 同时 更新户室信息
     * @param excelList
     */
    public void insertExcel_HouseMasterInfo(List<HouseMasterInfo> excelList){
        houseMasterInfoService.insertBatch(excelList);
        // 同步 更新 户室信息
        unitHouseService.updateIsHaveMasterAndHouseProportion(excelList.get(0).getCommunityId());
        unitHouseService.clearTCache();
    }

    /**
     * 将 错误数据 存在本地
     * @param list
     * @param url
     * @throws Exception
     */
    public void writeErrExcelData(List<HouseMasterInfo> list,String url) throws Exception{
        HSSFWorkbook wb = new HSSFWorkbook();
        // 在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("物业管理资源");
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.RED.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = wb.createFont();
        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = wb.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = wb.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("户主姓名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("户主性别");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("手机联系方式");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("座机联系方式");
        cell.setCellStyle(style);
        cell = row.createCell((short) 4);
        cell.setCellValue("单元名称");
        cell.setCellStyle(style);
        cell.setCellStyle(style);
        cell = row.createCell((short) 5);
        cell.setCellValue("房号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 6);
        cell.setCellValue("住宅面积(㎡)");
        cell.setCellStyle(style);
        cell = row.createCell((short) 7);
        cell.setCellValue("导入错误原因");
        cell.setCellStyle(style);
        // 写入实体数据 实际应用中这些数据从数据库得到，
        for (int i = 0; i < list.size(); i++){
            row = sheet.createRow((int) i + 1);
            row.createCell((short) 0).setCellValue( list.get(i).getHouseMasterName() );
            if(list.get(i).getHouseMasterSex()==1){
                row.createCell((short) 1).setCellValue("男");
            }
            if(list.get(i).getHouseMasterSex()==2){
                row.createCell((short) 1).setCellValue("女");
            }
            if(list.get(i).getHouseMasterSex()==3){
                row.createCell((short) 1).setCellValue("保密");
            }
            row.createCell((short) 2).setCellValue(list.get(i).getHouseMasterPhone());
            row.createCell((short) 3).setCellValue(list.get(i).getHouseMasterTelphone());
            row.createCell((short) 4).setCellValue(list.get(i).getUnitName());
            row.createCell((short) 5).setCellValue(list.get(i).getHouseNumber());
            row.createCell((short) 6).setCellValue(list.get(i).getHouseProportion());
            row.createCell((short) 7).setCellValue(list.get(i).getExcelErrRemarks());
        }
        // 第六步，将文件存到指定位置
        try
        {
            FileOutputStream fout = new FileOutputStream(url+File.separator+ DateUtil.format(new Date(), DateUtil.DATE_PATTERN.YYYYMMDDHHMMSS)+"户主信息导入错误数据.xls");
            logger.info("exportExcel, fileName:" + fout);
            wb.write(fout);
            fout.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
